//
//  AppDelegate.swift
//  Weibo201655
//
//  Created by pro on 16/5/5.
//  Copyright © 2016年 LeeDan. All rights reserved.
//

import UIKit

/// 全局共享 账号信息
// 全局变量 并不是程序一启动就加载 而是调用时才会从磁盘加载，且只加载一次，再次使用时从缓存中取
var sharedUserAccount = LDUserAccount.getUserAccount()//从沙盒加载用户信息

//切换控制器通知名称
let LDSwitchRootViewControllerNotification = "LDSwitchRootViewControllerNotification"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        //添加根控制器
        window?.rootViewController = wasLoginOrNot()
        //窗口可见
        window?.makeKeyAndVisible()
        
        //设置外观颜色
        setupAppearance()
        
        //接收切换控制器通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchController:", name: LDSwitchRootViewControllerNotification, object: nil)
        return true
    }
    
    /// 设置外观颜色
    func setupAppearance() {
        let item = UIBarButtonItem.appearance()
        item.tintColor = UIColor.orangeColor()
    }
    
    //MARK: 切换根控制器
    //程序启动时，上一次是否登陆过
    private func wasLoginOrNot()->UIViewController {
        
        return sharedUserAccount == nil ? LDMainTabBarController() : (isNewVersion() ? LDNewFeatureController() : LDWelcomeViewController())
    }
    //是否接收到要求切换控制器的通知（登录成功，切换欢迎界面；登录失败，不切换，回到登录界面）
    func switchController(notice: NSNotification) {

        window?.rootViewController = notice.object as! Bool == true ? LDWelcomeViewController() : LDMainTabBarController()
    }
    //判断是否是新版本（实际开发如何判断新版本）
    private func isNewVersion()->Bool {
        //获取当前版本
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        //获取沙盒版本
        let sandboxKey = "sandboxKey"
        let sandboxVersion = NSUserDefaults.standardUserDefaults().stringForKey(sandboxKey)
        //比较版本
        if currentVersion != sandboxVersion {
            //存储新版本到沙盒
            NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: sandboxKey)
            NSUserDefaults.standardUserDefaults().synchronize()
            return true
        }
        return false
    }
    
    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


    //MARK:- 注销通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: LDSwitchRootViewControllerNotification, object: nil)
    }
}

